<template>
    <div class="result-table-content">
        <h3>
            <el-row class="result-span">
                <el-col :span="3">
                    <span>风控结果:</span>
                    <status-tag :code="riskResultMsg.riskResult"></status-tag>
                </el-col>
                <el-col :span="6">
                    <span>试算/下单时间: </span>
                    <span style="color: red">{{ riskResultMsg.calcTime }}</span>
                </el-col>
                <el-col :span="5">
                    <span>计算耗时: </span>
                    <span style="color: red">{{ riskResultMsg.takeTime }}</span>
                </el-col>
                <el-col :span="6">
                    <span>条目检查数:</span>
                    <span v-show="riskResultMsg.riskResultTable.length" style="color: red">{{ riskResultMsg.riskResultTable.length }}</span>
                </el-col>
                <el-col :span="4">
                    <el-button style="float: right" type="primary" size="mini" @click="layoutDialog = true">布局设置</el-button>
                </el-col>
            </el-row>
        </h3>
        <div v-if="showFieldList.length" style="height: calc(100% - 35px)">
            <vxe-table
                ref="resultTable"
                :key="tableKey"
                :auto-resize="true"
                :data="riskResultMsg.riskResultTable"
                border
                size="mini"
                style="width: 100%"
                height="100%"
                v-loading="calcLoading"
                resizable
                :resizable-config="{ minWidth: '60' }"
                :sort-config="{ sortMethod: customSortMethod, defaultSort: { field: 'thresholdType', order: 'desc' } }"
                show-header-overflow
                :cell-style="getCellStyle"
                @filter-visible="handleFilterChange"
                align="center"
            >
                <vxe-column
                    v-for="(item, index) in showFieldList"
                    :key="index + item.id"
                    :field="item.id"
                    :title="item.content"
                    :sortable="item.sortable"
                    :column-config="{ isHover: true }"
                    :row-config="{ isHover: true }"
                    :filters="item.filters"
                    :filter-method="item.filterMethod"
                    :filter-render="{ name: 'FilterInput' }"
                    show-overflow
                    min-width="120"
                >
                    <template #filter="{ $panel, column }" v-if="item.filterType == 'search'">
                        <div>
                            <el-input
                                ref="searchInput"
                                class="my-input"
                                type="type"
                                v-for="(option, index) in column.filters"
                                :key="index"
                                v-model="option.data"
                                @input="$panel.changeOption($event, !!option.data, option)"
                            />
                        </div>
                    </template>
                    <template slot-scope="scope">
                        <span v-if="item.id === 'entryType'">{{ entryType[scope.row.entryType] }}</span>
                        <span v-else-if="item.id === 'compareType'">{{ compareDirection[scope.row.compareType] }}</span>
                        <status-tag v-else-if="item.id === 'thresholdType'" :code="scope.row.thresholdType" />
                        <branch-tag v-else-if="item.id === 'branchNum'" :data="scope.row" />
                        <span v-else-if="['investableBalance', 'maxTradable', 'maxTradableMerge'].includes(item.id)">
                            <el-popover
                                v-if="getObjectLength(scope.row[item.id]) && getObjectLength(scope.row[item.id]) > 1"
                                placement="top"
                                trigger="hover"
                            >
                                <div style="padding: 0 10px 10px 0" slot v-for="(value, key, index) in scope.row[item.id]" :key="key">
                                    {{ '阀值' + ++index + getShowName(item.id) + ': ' + scope.row[item.id][getParamName(item.id) + index] }}
                                </div>
                                <el-tag slot="reference">{{ getObjectLength(scope.row[item.id]) + '个' + getShowName(item.id) }}</el-tag>
                            </el-popover>
                            <span v-else-if="getObjectLength(scope.row[item.id])" v-for="(value, key) in scope.row[item.id]" :key="key">{{
                                value
                            }}</span>
                            <span v-else> --</span>
                        </span>
                        <span v-else-if="item.id === 'thresholdValue'">{{
                            scope.row[item.id] != undefined ? numberFormat(scope.row[item.id], scope.row.unit) + unitShow(scope.row.unit) : '--'
                        }}</span>

                        <span v-else-if="item.id === 'calculateValue'">
                            {{
                                scope.row[item.id] != undefined
                                    ? numberFormat(scope.row[item.id], !scope.row.unit || scope.row.unit == '无' ? 2 : scope.row.unit) +
                                      unitShow(scope.row.unit)
                                    : '--'
                            }}
                        </span>
                        <span v-else>{{ scope.row[item.id] || '--' }}</span>
                    </template>
                </vxe-column>
            </vxe-table>
        </div>

        <RiskTableLayout
            title="页面布局"
            :visible.sync="layoutDialog"
            :field-list="tableColumns"
            :selected-field-list="selectedFieldList"
            :fixed-field-list="fixedFieldList"
            :table-name="tableName"
            @on-submit="onSubmit"
        />
    </div>
</template>
<script lang="ts">
import RiskTableLayout from '@/common/components/risk-table-layout.vue';
import Invest from '@/common/dict/invest';
import BranchTag from '@/pages/risk-measure/components/branch-tag.vue';
import StatusTag from '@/pages/risk-measure/components/status-tag.vue';
import { numberFormat, sortBy, unitShow } from '@/utils/tools';
import { Vue, Component, Prop, Watch } from 'vue-property-decorator';
import { OrderClass } from '../class/order-class';
import ETFOrder from '../etf-inst/etf-order.vue';
import ColumnUtil from '../utils/column-util';
@Component({
    name: 'TrailResultPlus',
    components: {
        StatusTag,
        BranchTag,
        RiskTableLayout,
    },
})
/**
 * 指令下单页面 - 试算结果表格组件
 */
export default class TrailResultPlus extends Vue {
    @Prop()
    riskResultMsg: any;
    @Prop()
    tableName: string;
    Invest: any = new Invest(); // 指令相关字典类
    ColumnUtil = new ColumnUtil();

    tableKey: number = 0;
    calcLoading: boolean;
    tableData: any[] = [];
    entryType = {}; // 风险类型字典
    compareDirection = {}; // 比较方向字典
    entryTypeArr: any[] = []; // 风险类型
    ThresholdTypeArr: any[] = []; // 阈值类型
    layoutDialog: boolean = false; // 布局设置
    tableColumns = this.ColumnUtil.riskTableColumns; // 试算结果表格全部字段
    showFieldList: any[] = []; // 要显示的表格列
    selectedFieldList: any[] = []; // 已选择字段列表
    // 固定字段列表
    fixedFieldList: any[] = [
        { content: '产品代码', id: 'fundCode', sortable: true },
        { content: '产品名称', id: 'fundNameSt', sortable: false },
    ];

    numberFormat = numberFormat;
    unitShow = unitShow;
    iconDom: any = null;

    async mounted() {
        // 获取风险类型字典
        this.entryType = this.Invest.entryType;
        // 获取比较方向字典
        this.compareDirection = this.Invest.CompareDirection;
        this.entryTypeArr = this.objToArr(this.Invest.entryType);
        this.ThresholdTypeArr = this.objToArr(this.Invest.ThresholdType); // 获取阈值类型数据
        // this.queryLayout('ETF_OTDER');
    }

    @Watch('tableName', { immediate: true, deep: true })
    onWatchTableName() {
        if (this.tableName) {
            this.queryLayout(this.tableName);
        }
    }

    // 转表格筛选下拉框数据
    objToArr(param) {
        let list = [];
        for (let key in param) {
            list.push({ label: param[key], value: key });
        }
        return list;
    }

    handleFilterChange({ column, property, visible, filterList, $event }) {
        console.log({ column, property, visible, filterList, $event });
    }

    customSortMethod({ data, sortList }) {
        const sortItem = sortList[0];
        // 取出第一个排序的列
        const { property, order } = sortItem;
        let YHList = [];
        let NoYHlist = [];
        let list = [];
        let key = /^[a-zA-Z]+$/;
        data.forEach(ele => {
            if (ele.entryCode?.match('.*[A-Z]+.*') || ele.entryCode?.match('.*[a-z]+.*')) {
                YHList.push(ele);
            } else {
                NoYHlist.push(ele);
            }
        });

        if (order === 'asc' || order === 'desc') {
            if (property === 'entryCode') {
                YHList.sort(this.compare('entryCode'));
                NoYHlist.sort(this.compare('entryCode'));
                list = NoYHlist.concat(YHList);
                if (order === 'desc') {
                    list.reverse();
                }
            } else {
                list = data.slice().sort(sortBy(property, order));
            }
        }
        return list;
    }

    compare(property) {
        return function(a, b) {
            var value1 = a[property];
            var value2 = b[property];
            if (value1.length < 10 && value2.length < 10) {
                var f = '0000000000'; // 10个0
                var aa = f.substring(0, 10 - ('' + value1).length) + value1;
                var bb = f.substring(0, 10 - ('' + value2).length) + value2;
                return aa > bb ? 1 : -1;
            } else {
                return value1 > value2 ? 1 : -1;
            }
        };
    }

    // 获取对象长度
    getObjectLength(obj: any) {
        if (obj) {
            return Object.keys(obj).length;
        } else {
            return 0;
        }
    }

    // 获取可投余量、最大可交易量名称
    getShowName(name: string) {
        if (name == 'investableBalance') {
            return '可投余量';
        } else if (name == 'maxTradable') {
            return '最大可交易量';
        } else if (name == 'maxTradableMerge') {
            return '最大可交易量(汇总)';
        }
    }

    // 获取字段名
    getParamName(name: string) {
        return name == 'investableBalance' ? 'INVESTABLE_BALANCE_' : name == 'maxTradable' ? 'MAX_TRADABLE_' : 'MAX_TRADABLE_';
    }

    getCellStyle({ column }) {
        let value = 'padding: 0; text-align:center';
        let obj = this.ColumnUtil.riskTableColumns.find(item => item.id == column.property);
        if (obj) {
            value = 'padding: 0; text-align: ' + (obj.align || 'left');
        }
        return value;
    }

    // 表格列筛选数据
    filterHandler({ option, row, column }) {
        const property = column['property'];
        return row[property].includes(option.data);
    }

    /**
     * 获取页面布局信息
     */
    async queryLayout(tableName) {
        this.calcLoading = true;
        const resList: any = await new Promise((resolve, reject) => {
            this.$axios('/tableLayout/query/' + tableName)
                .then((res: any) => {
                    resolve(res);
                })
                .catch(err => {
                    reject(err);
                });
        });
        if (resList) {
            this.selectedFieldList = JSON.parse(resList);
            this.showFieldList = this.fixedFieldList.concat(this.selectedFieldList);
            this.calcLoading = false;
        } else {
            this.selectedFieldList = this.tableColumns;
            this.showFieldList = this.tableColumns;
            this.calcLoading = false;
        }
        // 设置筛选、排序条件
        this.showFieldList.forEach((ele: any) => {
            if (
                [
                    'fundCode',
                    'fundNameSt',
                    'assetCode',
                    'assetName',
                    'fundAccountCode',
                    'fundAccountName',
                    'stockCode',
                    'stockNameSt',
                    'entryCode',
                    'entryName',
                ].includes(ele.id)
            ) {
                this.$set(ele, 'filterMethod', this.filterHandler);
                // this.$set(ele, 'filters', [{ data: '' }]);
                // this.$set(ele, 'search', true);
            }
        });
        this.iconDom = null;
        // 重新渲染表格
        this.changeTable();
        this.tableKey++;
    }

    changeTable() {
        this.$nextTick(() => {
            const icon = [];
            if (!this.iconDom) {
                this.iconDom = document.querySelectorAll('.result-table-content .vxe-icon--funnel');
                this.iconDom.forEach((ele: any, index) => {
                    if (!['风险类型', '阈值类型'].includes(ele.parentNode.parentNode.children[0].innerHTML)) {
                        icon.push(index);
                    }
                });
                for (let i = 0; i < 22; i++) {
                    icon.forEach(ele => {
                        if (ele === i) {
                            this.iconDom[i].className = 'vxe-filter--btn el-icon-search';
                        }
                    });
                }
            }
        });
    }

    /**
     * 提交成功后回调
     * @param {Object} 回调数据
     */
    onSubmit(data) {
        this.queryLayout(this.tableName);
    }
}
</script>
<style lang="scss" scoped>
.result-table-content {
    height: 100%;
    .result-span {
        display: flex;
        align-items: center;
        margin-bottom: 5px;
        span {
            color: #575757;
        }
    }
}
.my-input {
    margin: 10px;
    width: 150px;
}
</style>
